using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Modeling;
using Microsoft.VisualStudio.Modeling.Diagrams;
using Microsoft.VisualStudio.Modeling.Shell;
using EnvDTE;
using System.IO;

namespace DslFactory.Utilities.DteCodeModel
{
 /// <summary>
 /// Set of utility methods enabling accessing information about the store when it is
 /// hosted into Visual Studio.
 /// </summary>
 public static class StoreCorrespondance
 {
  /// <summary>
  /// Get the filename in which a Store is persisted
  /// </summary>
  /// <param name="store"></param>
  public static string GetFileNameForStore(Store store)
  {
   foreach (Diagram diagram in store.ElementDirectory.FindElements<Diagram>(true))
   {
    VSDiagramView view = diagram.ActiveDiagramView as VSDiagramView;
    if (view != null)
    {
     // Get the corresponding file
     string filename = view.DocData.FileName;
     return filename;
    }
   }
   return string.Empty;
  }


  /// <summary>
  /// Get the project Item corresponding to the item in the store
  /// </summary>
  /// <param name="store"></param>
  /// <returns></returns>
  public static ProjectItem GetProjectItemForStore(Store store)
  {
   DTE dte = (DTE)store.GetService(typeof(DTE));
   if (dte != null)
    return dte.Solution.FindProjectItem(GetFileNameForStore(store));
   else
    return null;
  }

  /// <summary>
  /// Get the project in which the store is.
  /// </summary>
  /// <param name="store"></param>
  /// <returns></returns>
  public static Project GetProjectForStore(Store store)
  {
   ProjectItem projectItem = GetProjectItemForStore(store);
   if (projectItem == null)
    return null;
   else
    return projectItem.ContainingProject;
  }

  /// <summary>
  /// Get the default namespace of a store
  /// </summary>
  public static string GetDefaultNamespace(Store store)
  {
   Project project = GetProjectForStore(store);
   if (project == null)
    return string.Empty;

   if (project.Properties == null)
     return string.Empty;

    string projectDirectoryName = Path.GetDirectoryName(project.Properties.Item("FullPath").Value as string);
    string storeDirectory = Path.GetDirectoryName(GetFileNameForStore(store));
    if ((storeDirectory.StartsWith(projectDirectoryName))
         && (storeDirectory != projectDirectoryName)
       )
     return (project.Properties.Item("RootNamespace").Value as string) + "." + storeDirectory.Substring(projectDirectoryName.Length + 1);
    else
     return project.Properties.Item("RootNamespace").Value as string;
  }

 }
}
